import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getName, setName, removeName } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: getName(), // 从 Cookie 中恢复用户名
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
    // 持久化到 Cookie
    if (name) {
      setName(name)
    } else {
      removeName()
    }
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(async response => {
        const { data } = response
        
        // 设置token
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        
        // 设置用户信息
        if (data.nickname) {
          commit('SET_NAME', data.nickname)
        } else {
          commit('SET_NAME', username || 'Admin')
        }
        
        // 设置头像（使用默认头像）
        commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
        
        // 设置简介
        commit('SET_INTRODUCTION', '我是管理员')
        
        // 设置角色为admin，确保可以访问所有路由
        const roles = ['admin']
        commit('SET_ROLES', roles)
        
        if (data.uid) {
          // 如果需要存储用户ID，可以添加相应的mutation
          // commit('SET_USERID', data.uid)
        }

        // 生成路由并存储到vuex中
        try {
          // 根据角色生成可访问路由
          await dispatch('permission/generateRoutes', roles, { root: true })
        } catch (error) {
          console.error('生成路由失败:', error)
        }
        
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve) => {
      // 从 Cookie 或 state 中获取用户名
      const savedName = getName() || state.name || 'Admin'
      
      // 不再调用实际API，直接返回管理员信息
      const data = {
        roles: ['admin'],
        name: savedName,
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        introduction: '我是管理员'
      }
      
      commit('SET_ROLES', data.roles)
      commit('SET_NAME', data.name) // 这会保存到 Cookie
      commit('SET_AVATAR', data.avatar)
      commit('SET_INTRODUCTION', data.introduction)
      
      resolve(data)
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        commit('SET_ROLES', [])
        removeToken()
        removeName()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_ROLES', [])
      removeToken()
      removeName()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
